from django.shortcuts import render

from oauth.utils import generate_sign_openid
from .models import OAuthQQUser
from . import serializers
# Create your views here.
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from rest_framework.response import Response
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView,RetrieveAPIView ,UpdateAPIView
from rest_framework.permissions import IsAuthenticated

class OAuthQQLoginView(APIView):
    def get(self, request):
        # 1.获取参数  client_id=None, client_secret=None, redirect_uri=None, state=None
        state = request.query_params.get("state", "/")
        # 2.创建对象
        oauthqq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                          client_secret=settings.QQ_CLIENT_SECRET,
                          redirect_uri=settings.QQ_REDIRECT_URI,
                          state=state)
        # 3.返回qq登陆页面
        login_url = oauthqq.get_qq_url()
        return Response({"auth_url": login_url})


class OAuthQQUserView(GenericAPIView):
    serializer_class = serializers.OAuthQQUserSerializer

    def get(self, request):
        # 1.获取参数code,校验
        code = request.query_params.get("code")
        if not code:
            return Response("code丢失")
        # 2.根据code获取access_token
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI, )
        access_token = oauth_qq.get_access_token(code)
        # 3.根据access_token获取openid
        openid = oauth_qq.get_open_id(access_token)
        # return  Response("openid = %s"%openid)
        # 4.通过openid查询qq对象用户
        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 初次授权
            sign_openid = generate_sign_openid(openid)
            return Response({"access_token": sign_openid})
        else:
            # 非初次授权
            user = oauth_qq_user.user
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return Response({

            "token": token,
            "username": user.username,
            "user_id": user.id
        })

    def post(self, request):
        # 1.获取参数
        dict_data = request.data

        # 2.创建序列化器
        serializer = self.get_serializer(data=dict_data)

        # 3.校验，入库
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        # 3.1根据用户数据，生成token
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 4,返回响应
        return Response({
            "token": token,
            "user_id": user.id,
            "username": user.username})


